package com.hbm.usercenter.base;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.hbm.usercenter.base.LoadingPager.LoadedResult;
import com.hbm.usercenter.utils.UIUtils;

import java.util.List;
import java.util.Map;

public abstract class BaseFragment extends Fragment {
    private LoadingPager mLoadingPager;

    public LoadingPager getLoadingPager() {
        return mLoadingPager;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {

        if (mLoadingPager == null) {
            mLoadingPager = new LoadingPager(UIUtils.getContext()) {

                @Override
                protected LoadedResult initData() {
                    return BaseFragment.this.initData();
                }

                @Override
                protected View initSuccessView() {
                    return BaseFragment.this.initSuccessView();
                }

            };
        } else {
            ViewParent parent = mLoadingPager.getParent();
            if (parent != null && parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(mLoadingPager);
            }
        }
        mLoadingPager.triggerLoadData();
        return mLoadingPager;

    }

    protected abstract LoadedResult initData();

    protected abstract View initSuccessView();

    public LoadedResult checkState(Object obj) {
        if (obj == null) {
            return LoadedResult.EMPTY;
        }
        if (obj instanceof List) {
            if (((List) obj).size() == 0) {
                return LoadedResult.EMPTY;
            }
        }
        if (obj instanceof Map) {
            if (((Map) obj).size() == 0) {
                return LoadedResult.EMPTY;
            }
        }
        return LoadedResult.SUCCESS;
    }

}
